package com.weixin.webCoding;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName TcpTest
 * @Description
 * @date 2022/2/17 16:55
 * @author: wx
 * @Version 1.0
 */
public class TcpTest {

    //客户端
    @Test
    public void client() throws IOException {
        InetAddress ip = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(ip, 8001);
        OutputStream ops = socket.getOutputStream();
        ops.write("我是客户端".getBytes(StandardCharsets.UTF_8));
        ops.close();
        socket.close();
    }

    //服务端
    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8001);
        Socket socket = serverSocket.accept();
        InputStream ips = socket.getInputStream();
        //使用数组可能出现数据不确定问题
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[10];
        int len;
        while((len = ips.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }
        System.out.println(bos.toString());
        bos.close();
        socket.close();
    }
}
